package com.yiqi.liebang.common.rongim;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.entity.bo.UserInfoBo;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.yiqi.liebang.common.rongim.db.UserOpe;
import com.yiqi.liebang.common.rongim.pinyin.CharacterParser;
import com.yiqi.liebang.common.rongim.ui.MyExtensionModule;

import cn.rongcloud.contactcard.Friend;

import com.yiqi.liebang.entity.bo.PeopleBo;
import com.yiqi.liebang.feature.mine.view.UserInfoActivity;
import com.yiqi.liebang.framework.api.UserApi;

import java.util.ArrayList;
import java.util.List;

import cn.rongcloud.contactcard.ContactCardExtensionModule;
import cn.rongcloud.contactcard.IContactCardInfoProvider;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.LocationMessage;

public class SealAppContext implements
        RongIMClient.ConnectionStatusListener, RongIM.ConversationBehaviorListener, RongIM.ConversationListBehaviorListener,
        RongIM.UserInfoProvider, RongIM.GroupInfoProvider, RongIM.LocationProvider,
        RongIM.IGroupMembersProvider, RongIM.ConversationClickListener, RongIMClient.OnReceiveMessageListener {

    private static final int CLICK_CONVERSATION_USER_PORTRAIT = 1;


    private final static String TAG = "SealAppContext";
    public static final String UPDATE_FRIEND = "update_friend";
    public static final String UPDATE_RED_DOT = "update_red_dot";
    public static final String UPDATE_GROUP_NAME = "update_group_name";
    public static final String UPDATE_GROUP_MEMBER = "update_group_member";
    public static final String GROUP_DISMISS = "group_dismiss";

    private Context mContext;

    private static SealAppContext mRongCloudInstance;
    List<Friend> mData;

    private static ArrayList<Activity> mActivities;

    public SealAppContext(Context mContext) {
        this.mContext = mContext;
        SealUserInfoManager.init(mContext);
        mActivities = new ArrayList<>();
        initListener();
    }

    /**
     * 初始化 RongCloud.
     *
     * @param context 上下文。
     */
    public static void init(Context context) {

        if (mRongCloudInstance == null) {
            synchronized (SealAppContext.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new SealAppContext(context);
                }
            }
        }

    }

    /**
     * init 后就能设置的监听
     */
    private void initListener() {
        RongIM.setConversationBehaviorListener(this);//设置会话界面操作的监听器。
        RongIM.setConversationListBehaviorListener(this);
        RongIM.setConnectionStatusListener(this);
        RongIM.setUserInfoProvider(this, true);
        RongIM.setGroupInfoProvider(this, true);
        RongIM.setLocationProvider(this);//设置地理位置提供者,不用位置的同学可以注掉此行代码
        RongIM.setOnReceiveMessageListener(this);
//        setInputProvider();
        //setUserInfoEngineListener();//移到SealUserInfoManager
//        setReadReceiptConversationType();
        RongIM.getInstance().enableNewComingMessageIcon(true);
        RongIM.getInstance().enableUnreadMessageIcon(true);
        RongIM.getInstance().setGroupMembersProvider(this);
        RongIM.getInstance().setConversationClickListener(this);
    }

    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static SealAppContext getInstance() {
        return mRongCloudInstance;
    }

    public Context getContext() {
        return mContext;
    }


    public RongIMClient.ConnectCallback getConnectCallback() {
        RongIMClient.ConnectCallback connectCallback = new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Logger.d(TAG, "ConnectCallback connect onTokenIncorrect");
//                SealUserInfoManager.getInstance().reGetToken();
            }

            @Override
            public void onSuccess(String s) {
                Logger.d(TAG, "ConnectCallback connect onSuccess");
//                T.showShort("连接成功");
                setMyExtensionModule();
                inits();
                UserInfoBo userInfoBo = AM.user().getLoginResultCache();
                RongIM.getInstance().setCurrentUserInfo(new UserInfo(userInfoBo.getUserUid(), userInfoBo.getUserName(),
                        TextUtils.isEmpty(userInfoBo.getUserHead()) ? Uri.parse("") : Uri.parse(userInfoBo.getUserHead())));
//                SharedPreferences sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
//                sp.edit().putString(SealConst.SEALTALK_LOGIN_ID, s).commit();
            }

            @Override
            public void onError(final RongIMClient.ErrorCode e) {
                T.showShort("连接失败" + e.getMessage());
                Logger.d(TAG, "ConnectCallback connect onError-ErrorCode=" + e);
            }
        };
        return connectCallback;
    }


    @Override
    public void onChanged(ConnectionStatus connectionStatus) {

    }

    private void inits() {


        AM.api().createApiService(UserApi.class)
                .getMyFriendList(new PeopleBo())
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<List<Friend>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(List<Friend> friends) {
                        mData = new ArrayList<>();
                        mData = friends;
                        try {
                            UserOpe.deleteAllData(mContext);
                            UserOpe.insertData(mContext, mData);
                        } catch (Exception e) {
                            Logger.e("" + e.getMessage());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        T.showShort(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    public static void initCARD(List<Friend> friends) {
        T.showShort("initCARD--->");
        //             RongExtensionManager.getInstance().registerExtensionModule(new RecognizeExtensionModule());
        RongExtensionManager.getInstance().registerExtensionModule(new ContactCardExtensionModule(new IContactCardInfoProvider() {
            @Override
            public void getContactAllInfoProvider(final IContactCardInfoCallback contactInfoCallback) {
                contactInfoCallback.getContactCardInfoCallback(friends);
            }


            public void getContactAppointedInfoProvider(String userId, String name, String portrait, final IContactCardInfoCallback contactInfoCallback) {
                contactInfoCallback.getContactCardInfoCallback(friends);
            }

        }, (view, content) -> {
            T.showShort("click-->");
            Intent intent = new Intent(view.getContext(), UserInfoActivity.class);
            Friend friend = SealUserInfoManager.getInstance().getFriendByID(content.getId());
            if (friend == null) {
                UserInfo userInfo = new UserInfo(content.getId(), content.getName(),
                        Uri.parse(TextUtils.isEmpty(content.getImgUrl()) ? RongGenerate.generateDefaultAvatar(content.getName(), content.getId()) : content.getImgUrl()));
                friend = CharacterParser.getInstance().generateFriendFromUserInfo(userInfo);
            }
            intent.putExtra("friend", friend);
            view.getContext().startActivity(intent);
        }));
    }

    public void setMyExtensionModule() {
        List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules();
        IExtensionModule defaultModule = null;
        if (moduleList != null) {
            for (IExtensionModule module : moduleList) {
                if (module instanceof DefaultExtensionModule) {
                    defaultModule = module;
                    break;
                }
            }
            if (defaultModule != null) {
                RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule);
                RongExtensionManager.getInstance().registerExtensionModule(new MyExtensionModule());
            }
        }
    }

    public void logout() {
        RongIM.getInstance().disconnect();
        RongIM.getInstance().logout();
    }

    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        if (userInfo != null && AM.user().isLogin()) {
            if (AM.user().getLoginResultCache().getUserUid().equals(userInfo.getUserId())) {
                Intent intent = new Intent(context, UserInfoActivity.class);
                intent.putExtra("is_view_my", true);
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(context, UserInfoActivity.class);
                intent.putExtra("is_view_my", false);
                intent.putExtra("visitorUid", userInfo.getUserId());
                context.startActivity(intent);
            }
        }

        return false;
    }

    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {

        return false;
    }

    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {

        return false;
    }

    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {

        return false;
    }

    @Override
    public boolean onMessageClick(Context context, View view, Message message) {
        Logger.e(message.getContent().toString());
        if (message.getObjectName().equals("RC:LBSMsg")){
            LocationMessage locationMessage= (LocationMessage) message.getContent();
            Intent intent=new Intent(context,LocationActivity.class);
            intent.putExtra("loc",locationMessage);
            context.startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    public boolean onMessageLinkClick(Context context, String s, Message message) {
        return false;
    }

    @Override
    public boolean onMessageLinkClick(Context context, String s) {
        return false;
    }

    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        return false;
    }

    @Override
    public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
        Intent intent = new Intent(context, UserInfoActivity.class);
        intent.putExtra("is_view_my", false);
        intent.putExtra("visitorUid", s);
        context.startActivity(intent);
        return true;
    }

    @Override
    public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
        return false;
    }

    @Override
    public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    @Override
    public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
        return false;
    }

    @Override
    public UserInfo getUserInfo(String s) {
        List<Friend> friends = mData;
        if (friends != null && friends.size() > 0) {
            //增强for把所有的用户信息 return 给融云
            for (Friend friend : friends) {
                //判断返回的userId
                if (friend != null) {
                    if (friend.getUserUid().equals(s)) {
                        return new UserInfo(friend.getUserUid(), friend.getUserName(),
                                TextUtils.isEmpty(friend.getUserHead()) ? Uri.parse("") : Uri.parse(friend.getUserHead()));
                    }
                }
            }
        }
        SealUserInfoManager.getInstance().getUserInfo(s);
        return null;
    }

    @Override
    public Group getGroupInfo(String s) {
        return null;
    }

    @Override
    public void onStartLocation(Context context, LocationCallback locationCallback) {

    }

    @Override
    public void getGroupMembers(String s, RongIM.IGroupMemberCallback iGroupMemberCallback) {

    }

    /**
     * @param message 收到的消息实体。
     * @param i
     * @return
     */
    @Override
    public boolean onReceived(Message message, int i) {
//        T.showShort("onReceived---------->");
        return false;
    }

}